<template>
  <!-- 面包屑导航区域 -->
  <breadcrumb :childMenu="['用户管理', '用户列表']"></breadcrumb>
  <!-- 卡片视图区域 -->
  <el-card>
    <!-- 搜索与添加区域 -->
    <el-row :gutter="20">
      <el-col :span="10">
        <el-input
          placeholder="请输入内容"
          v-model="queryInfo.searchTerm"
          clearable
          @clear="getUserList"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="getUserList"></el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="addDialogVisible = true"
          >添加用户</el-button
        >
      </el-col>
    </el-row>
    <!-- 用户列表区域 -->
    <el-table :data="userList" border stripe size="mini">
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column label="姓名" prop="userName"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="电话" prop="phoneNumber"></el-table-column>
      <el-table-column label="角色" prop="roleName"></el-table-column>
      <el-table-column label="状态">
        <template v-slot="slotProps">
          <el-switch
            v-model="slotProps.row.isActive"
            @change="isActiveChanged(slotProps.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template v-slot="slotProps">
          <!-- 修改 -->
          <el-tooltip
            effect="dark"
            content="修改"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(slotProps.row.id)"
            >
            </el-button>
          </el-tooltip>
          <!-- 删除 -->
          <el-tooltip
            effect="dark"
            content="删除"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(slotProps.row.id)"
            >
            </el-button>
          </el-tooltip>
          <!-- 分配角色 -->
          <el-tooltip
            effect="dark"
            content="分配角色"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRole(slotProps.row)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :pageInfo="pageInfo"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    ></el-pagination>
  </el-card>
  <!-- 添加用户的表单对话框 -->
  <add-user-form
    :addDialogVisible="addDialogVisible"
    :addFromRules="formRules"
    @addDialogClose="addDialogClose"
  ></add-user-form>
  <!-- 修改用户的表单对话框 -->
  <edit-user-form
    :editDialogVisible="editDialogVisible"
    :editForm="editForm"
    :editFormRules="formRules"
    @editDialogClose="editDialogClose"
  ></edit-user-form>
  <!-- 设置用户角色对话框 -->
  <set-role-dialog
    :setRoleDialogVisible="setRoleDialogVisible"
    :userInfo="userInfo"
    :roleList="roleList"
    @setRoleDialogClose="setRoleDialogClose"
  ></set-role-dialog>
</template>

<script>
import Breadcrumb from "@/common/Breadcrumb.vue";
import ElPagination from "@/common/ElPagination.vue";
import AddUserForm from "./childComponents/AddUserForm.vue";
import EditUserForm from "./childComponents/EditUserForm.vue";
import SetRoleDialog from "./childComponents/SetRoleDialog.vue";
import {
  getUserList,
  patchUser,
  getUserInfo,
  deleteUser
} from "network/user.js";
import { getRoleList } from "network/role.js";
import { getMenus } from "network/permissions.js";
export default {
  components: {
    Breadcrumb,
    ElPagination,
    EditUserForm,
    AddUserForm,
    SetRoleDialog
  },
  data() {
    //校验邮箱的验证规则
    var checkEmail = (rule, value, callback) => {
      //验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        //合法的邮箱
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    // 校验手机号的验证规则
    var checkPhoneNumber = (rule, value, callback) => {
      //验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        //合法的手机号
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      // 表单的验证规则对象
      formRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "密码的长度在3~15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhoneNumber, trigger: "blur" }
        ]
      },
      //查询信息
      queryInfo: {
        searchTerm: "",
        pageIndex: 1,
        pageSize: 5
      },
      //用户集合
      userList: [],
      //分页信息
      pageInfo: [],
      //需要进行局部更新的字段的集合
      patchDocument: [],
      //需要局部更新的字段
      patchUser: {
        op: "add",
        path: "",
        value: ""
      },
      //保存查询到的用户信息对象
      editForm: {},
      //显示隐藏添加用户对话框
      addDialogVisible: false,
      //显示隐藏修改用户的对话框
      editDialogVisible: false,
      //显示隐藏设置用户角色的对话框
      setRoleDialogVisible: false,
      //要分配角色的用户信息
      userInfo: {},
      //分配角色下拉框绑定的角色列表
      roleList: {}
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const res = await getUserList(this.queryInfo);
      if (!res) return;
      // console.log(res);
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.data });
      this.userList = res.response;
      this.pageInfo.totalCount = res.totalCount;
      this.pageInfo.pageIndex = res.pageIndex;
      this.pageInfo.pageSize = res.pageSize;
      // console.log(this.userList);
    },
    //页面数据量改变
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    //页码值改变
    handleCurrentChange(newPageIndex) {
      this.queryInfo.pageIndex = newPageIndex;
      this.getUserList();
    },
    //监听switch开关状态的改变
    async isActiveChanged(row) {
      this.patchDocument = [];
      this.patchUser.path = "/isActive";
      this.patchUser.value = row.isActive;
      this.patchDocument.push(this.patchUser);
      // console.log(this.patchDocument);
      await patchUser(row.id, this.patchDocument);
    },
    // 展示编辑对话框
    async showEditDialog(id) {
      const res = await getUserInfo(id);
      if (!res.status)
        return this.$message.error({ showClose: true, msg: res.messgae });
      this.editForm = res.response;
      this.editDialogVisible = true;
    },
    //添加新用户对话框关闭
    addDialogClose(isReload) {
      this.addDialogVisible = false;
      if (isReload) this.getUserList();
    },
    //修改用户对话框关闭
    editDialogClose() {
      this.editDialogVisible = false;
    },
    //根据id删除对应的用户信息
    removeUserById(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          //如果用户确定删除,则返回值为字符串'confirm'
          const res = await deleteUser(id);
          if (res.status === 200) {
            this.$message.success({
              showClose: true,
              message: res.msg
            });
            return this.getUserList();
          } else
            return this.$message.error({
              showClose: true,
              message: res.msg
            });
        })
        .catch(() => {
          //如果用户取消了删除,则返回值为字符串'cancel'
          this.$message.info({
            showClose: true,
            message: "已取消删除!"
          });
        });
    },
    //分配角色
    async setRole(userInfo) {
      this.userInfo = userInfo;
      //在展示对话框之前,获取所有角色的列表
      const res = await getRoleList();
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      this.roleList = res.response;
      this.setRoleDialogVisible = true;
    },
    //关闭分配角色页面
    setRoleDialogClose(isReload) {
      if (isReload) {
        this.getUserList();
      }
      this.setRoleDialogVisible = false;
    }
  }
};
</script>

<style lang="less" scoped></style>
